#!/usr/bin/python -S
"""
interleave.py
"""

__author__ = 'Andy Chu'


import os
import sys

import tnet


class Error(Exception):
  pass


def main(argv):
  """Returns an exit code."""

  boundary = os.getenv('PGI_BOUNDARY')
  assert boundary, 'PGI_BOUNDARY required'

  while True:
    try:
      request = tnet.load(sys.stdin)
    except EOFError:
      break

    # initial 
    header = {'stdout_boundary': boundary}
    sys.stdout.write(tnet.dumps(header))

    lines = int(request['argv'][0])
    for i in xrange(lines):
      print 'stdout: %d' % i
      print >>sys.stderr, 'stderr: %d' % i

    print 'pid', os.getpid()

    # end stdout
    print boundary
    # end stderr
    print >>sys.stderr, boundary

    trailer = {'status': 0}
    sys.stdout.write(tnet.dumps(trailer))

    # This is necessary
    sys.stdout.flush()


  return 0


if __name__ == '__main__':
  sys.exit(main(sys.argv))
